/*
 * Copyright 2011 Philippe Blanc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package me.l1k3.fx.client;

import java.util.ArrayList;

import com.google.gwt.dom.client.Element;

import me.l1k3.fx.client.channel.ShowAndHideChannel;
import me.l1k3.fx.client.channel.inter.Channel;
import me.l1k3.fx.client.impl.FXShowAndHideAbstract;
import me.l1k3.fx.client.inter.FX;

public class FXChannel extends FXShowAndHideAbstract {
	private ArrayList<Channel> channels = new ArrayList<Channel>();
	private ShowAndHideChannel showAndHideChannel;
	
	//- - - factory
	
    public final static FXChannel create(Element element) {
        FXChannel channel = new FXChannel();
        channel.init(element);
        
        return channel;
    }
	
    //- - -
    
    @Override
    public boolean isVisible() {
        if(showAndHideChannel!=null) {
            return showAndHideChannel.isForward();
        }
        
        return true;
    }
    
	//- - -
    
	public void add(Channel channel) {
	    channels.add(channel);
	    
	    if(context!=null) {
	        channel.init(context);
		    validateChannel(channel);
	    }
	}
	
   public final void setHideAndShow(boolean hideAndShow, boolean backward) {
        if(hideAndShow && showAndHideChannel==null) {         
            showAndHideChannel = ShowAndHideChannel.hideAndShow(backward);
            add(showAndHideChannel);
        }
    }
	
    //- - -	
	
	/**
     * @exclude
     */
    @Override
    public FX init(Element element) {
        super.init(element);
        for (Channel channel : channels) {
            channel.init(context);
            validateChannel(channel);
        }
        
        return this;
    }
	
    /**
     * @exclude
     */
    @Override
	public FX toggle() {
		for (Channel channel : channels) {
			channel.toggle(context);
		}
		
		return this;
	}

    /**
     * @exclude
     */
	@Override
	public void onStart() {
	    super.onStart();
		for (Channel channel : channels) {
			channel.start(context);
		}
	}
	
	/**
     * @exclude
     */
    @Override
    public void onUpdate(double progress) {
        context.setProgress(progress);
        
        for (Channel channel : channels) {
            channel.update(context);
        }
    }	
	
    /**
     * @exclude
     */
	@Override
	public void onComplete() {
		for (Channel channel : channels) {
			channel.complete(context);
		}
		super.onComplete();
	}
}
